package com.luozengliang.exam.bus;

import com.luozengliang.exam.entity.Fruit;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Order {
    // 购物车
    private List<Fruit> cart = new ArrayList<Fruit>();
    // 商品折扣，水果名称——折扣（小数形式)
    private Map<String, BigDecimal> discount = new HashMap<>();
    // 满减
    private BigDecimal full;
    private BigDecimal reduce;

    //添加购物车
    public void addCart(Fruit fruit){
        cart.add(fruit);
    }

    //移除购物车
    public void removeCart(Fruit fruit){
        cart.remove(fruit);
    }

    //添加折扣
    public void setDiscount(String name, BigDecimal discount){
        this.discount.put(name, discount);
    }

    //移除折扣
    public void removeDiscount(String name){
        this.discount.remove(name);
    }

    // 设置满减
    public void setFullReduce(BigDecimal full, BigDecimal reduce) {
        this.full = full;
        this.reduce = reduce;
    }

    /**
     * 获取最终订单价格
     * @return 订单价格
     */
    public BigDecimal getFinalPrice() {
        BigDecimal finalPrice = new BigDecimal("0");
        for (Fruit fruit : cart) {
            // 判断该水果是否有折扣
            if (this.discount.get(fruit.getName()) != null) {
                finalPrice = finalPrice.add(fruit.totalPrice().multiply(this.discount.get(fruit.getName()))
                        .setScale(2, RoundingMode.HALF_UP));
            }else {
                finalPrice = finalPrice.add(fruit.totalPrice());
            }

        }

        //判断是否有满减活动
        if (this.full != null && this.reduce != null) {
            finalPrice = finalPrice.subtract(finalPrice.divide(this.full, 0, RoundingMode.DOWN).multiply(this.reduce))
                    .setScale(2, RoundingMode.HALF_UP);
        }

        return finalPrice;
    }
}
